document.addEventListener('DOMContentLoaded', function() {
    const API_BASE_URL = 'http://172.20.10.3:8080/api/data';

    // 初始化所有图表
    initSalesChart(API_BASE_URL);
    initProvinceCharts(API_BASE_URL);
    initGenderChart(API_BASE_URL);
    initBrandChart(API_BASE_URL);
    
    // --- 调用新增的图表初始化函数 ---
    initAgeChart(API_BASE_URL);
    initCategoryChart(API_BASE_URL);
});

/**
 * 每日销售额趋势图
 */
async function initSalesChart(baseUrl) {
    const chart = echarts.init(document.getElementById('sales-chart'));
    chart.showLoading();

    try {
        const response = await fetch(`${baseUrl}/sales`);
        const data = await response.json();

        const dates = data.map(item => item.date);
        const values = data.map(item => item.totalSales);

        const option = {
            tooltip: { trigger: 'axis', formatter: '{b}<br/>销售额: ¥ {c}' },
            xAxis: { type: 'category', boundaryGap: false, data: dates },
            yAxis: { type: 'value', axisLabel: { formatter: '¥ {value}' } },
            grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
            series: [{
                name: '销售额', type: 'line', smooth: true, areaStyle: {},
                data: values, itemStyle: { color: '#0052cc' }
            }]
        };
        chart.setOption(option);
    } catch (error) {
        console.error('Failed to load sales data:', error);
    } finally {
        chart.hideLoading();
    }
}

/**
 * 省份分布图（地图和柱状图）
 */
async function initProvinceCharts(baseUrl) {
    const mapChart = echarts.init(document.getElementById('province-map-chart'));
    const barChart = echarts.init(document.getElementById('province-bar-chart'));
    mapChart.showLoading();
    barChart.showLoading();

    try {
        const response = await fetch(`${baseUrl}/province`);
        const data = await response.json();
        
        const mapData = data.map(item => ({ name: item.province, value: item.count }));
        const top10Data = data.slice(0, 10).reverse();
        const topProvinces = top10Data.map(item => item.province);
        const topCounts = top10Data.map(item => item.count);
        const maxCount = data.length > 0 ? Math.max(...data.map(d => d.count)) : 0;

        const mapOption = {
            tooltip: { trigger: 'item', formatter: '{b}: {c} 人' },
            visualMap: {
                min: 0, max: maxCount, left: 'left', top: 'bottom',
                text: ['高', '低'], calculable: true,
                inRange: { color: ['#e0f3ff', '#0052cc'] }
            },
            series: [{
                name: '用户省份分布', type: 'map', map: 'china',
                roam: true, label: { show: false }, data: mapData
            }]
        };

        const barOption = {
            tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
            xAxis: { type: 'value', boundaryGap: [0, 0.01] },
            yAxis: { type: 'category', data: topProvinces },
            grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
            series: [{
                name: '用户数', type: 'bar', data: topCounts,
                itemStyle: { color: '#0052cc' }
            }]
        };

        mapChart.setOption(mapOption);
        barChart.setOption(barOption);

    } catch (error) {
        console.error('Failed to load province data:', error);
    } finally {
        mapChart.hideLoading();
        barChart.hideLoading();
    }
}

/**
 * 性别分布图
 */
async function initGenderChart(baseUrl) {
    const chart = echarts.init(document.getElementById('gender-chart'));
    chart.showLoading();
    try {
        const response = await fetch(`${baseUrl}/gender`);
        const data = await response.json();

        const option = {
            tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c} ({d}%)' },
            legend: { top: 'bottom' },
            series: [{
                name: '性别分布', type: 'pie', radius: '55%',
                data: data,
                emphasis: {
                    itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' }
                }
            }]
        };
        chart.setOption(option);
    } catch (error) {
        console.error('Failed to load gender data:', error);
    } finally {
        chart.hideLoading();
    }
}

/**
 * 品牌销售图
 */
async function initBrandChart(baseUrl) {
    const chart = echarts.init(document.getElementById('brand-chart'));
    chart.showLoading();

    const DATA_TYPES = {
        SALES: 'sales',
        COUNT: 'count'
    };

    let currentDataType = DATA_TYPES.SALES;
    let originalData = [];

    try {
        const response = await fetch(`${baseUrl}/brand/all`);
        originalData = await response.json();

        updateChart();
        createToggleButton();
        setInterval(toggleDataType, 5000);
    } catch (error) {
        console.error('Failed to load brand data:', error);
    } finally {
        chart.hideLoading();
    }

    function updateChart() {
        const formattedData = originalData.map(item => ({
            name: item.brand,
            value: currentDataType === DATA_TYPES.SALES ? item.totalSales : item.totalCount,
            sales: item.totalSales,
            count: item.totalCount
        }));

        const option = {
            tooltip: {
                trigger: 'item',
                formatter: function(params) {
                    const salesValue = params.data.sales.toLocaleString('zh-CN', {
                        style: 'currency',
                        currency: 'CNY'
                    });
                    return `${params.data.name}<br/>销售额: ${salesValue}<br/>数量: ${params.data.count}`;
                }
            },
            series: [{
                type: 'treemap',
                roam: false,
                nodeClick: false,
                breadcrumb: { show: false },
                data: formattedData,
                label: {
                    formatter: function(params) {
                        return params.data.name; // 只显示品牌名称
                    }
                }
                // 移除所有可能影响颜色的配置，使用 ECharts 默认颜色方案
            }]
        };

        chart.setOption(option);
    }

    function toggleDataType() {
        currentDataType = currentDataType === DATA_TYPES.SALES ? DATA_TYPES.COUNT : DATA_TYPES.SALES;
        updateChart();

        const button = document.getElementById('toggle-data-type');
        if (button) {
            button.textContent = `切换至${currentDataType === DATA_TYPES.SALES ? '数量' : '销售额'}`;
        }
    }

    function createToggleButton() {
        const container = document.getElementById('brand-chart-container');
        if (!container) return;

        const button = document.createElement('button');
        button.id = 'toggle-data-type';
        button.className = 'btn btn-primary mt-2';
        button.textContent = '切换至数量';
        button.onclick = toggleDataType;

        container.appendChild(button);
    }
}

// --- 以下为新增的图表函数 ---

/**
 * 年龄段分布图 (饼图)
 */
async function initAgeChart(baseUrl) {
    const chart = echarts.init(document.getElementById('age-chart'));
    chart.showLoading();
    try {
        const response = await fetch(`${baseUrl}/age`);
        const data = await response.json();

        const option = {
            tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c}人 ({d}%)' },
            legend: {
                orient: 'vertical',
                left: 'left',
                top: 'center'
            },
            series: [{
                name: '年龄段分布',
                type: 'pie',
                radius: ['40%', '70%'], // 制作成环形图
                avoidLabelOverlap: false,
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '20',
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false
                },
                data: data
            }]
        };
        chart.setOption(option);
    } catch (error) {
        console.error('Failed to load age data:', error);
    } finally {
        chart.hideLoading();
    }
}

/**
 * 热门商品类别销售额 (条形图)
 */
// 解析类别层级结构并计算各级别销售额
function parseCategoryHierarchy(data) {
    const hierarchy = {};

    data.forEach(item => {
        const categories = item.categories;
        const value = item.value;

        if (!categories || categories.length === 0) return;

        // 获取或创建顶级类别
        const topCategory = categories[0];
        if (!hierarchy[topCategory]) {
            hierarchy[topCategory] = {
                name: topCategory,
                total: 0,
                children: {}
            };
        }

        // 累加顶级类别总销售额
        hierarchy[topCategory].total += value;

        // 如果有子类别，处理子类别
        if (categories.length > 1) {
            const subCategory = categories[categories.length - 1]; // 取最后一级作为子类别
            if (!hierarchy[topCategory].children[subCategory]) {
                hierarchy[topCategory].children[subCategory] = 0;
            }
            hierarchy[topCategory].children[subCategory] += value;
        }
    });

    return hierarchy;
}

// 准备堆叠柱状图数据
function prepareStackedBarData(hierarchy, mainCategories) {
    const seriesData = [];
    const subCategories = new Set();

    // 收集所有子类别
    mainCategories.forEach(cat => {
        const children = hierarchy[cat.name].children;
        Object.keys(children).forEach(subCat => subCategories.add(subCat));
    });

    // 为每个子类别创建一个系列
    Array.from(subCategories).forEach(subCategory => {
        const seriesItem = {
            name: subCategory,
            type: 'bar',
            stack: 'total',
            data: mainCategories.map(mainCat => {
                const children = hierarchy[mainCat.name].children;
                return children[subCategory] || 0;
            })
        };
        seriesData.push(seriesItem);
    });

    return seriesData;
}

async function initCategoryChart(baseUrl) {
    const chart = echarts.init(document.getElementById('category-chart'));
    chart.showLoading();

    try {
        const response = await fetch(`${baseUrl}/category`);
        const data = await response.json();

        const hierarchyData = parseCategoryHierarchy(data);

        const mainCategories = Object.keys(hierarchyData)
            .map(key => ({
                name: key,
                value: hierarchyData[key].total
            }))
            .sort((a, b) => b.value - a.value)
            .slice(0, 10);

        const seriesData = prepareStackedBarData(hierarchyData, mainCategories);

        const option = {
            tooltip: {
                trigger: 'item',
                backgroundColor: 'rgba(255, 255, 255, 0.9)',
                borderColor: '#ccc',
                borderWidth: 1,
                textStyle: {
                    color: '#333'
                },
                formatter: function(params) {
                    const mainCategory = params.name;
                    const subCategory = params.seriesName;
                    const value = params.value;
                    const percent = ((value / hierarchyData[mainCategory].total) * 100).toFixed(1);

                    return `
                        <div style="font-weight:bold;">${mainCategory} > ${subCategory}</div>
                        <div>销售额: ${value.toFixed(2)} 元</div>
                        <div>占比: ${percent}%</div>
                    `;
                }
            },
            grid: {
                left: '3%',
                right: '3%',
                bottom: '15%', // 为缩放条腾出空间
                top: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: mainCategories.map(cat => cat.name),
                axisLabel: {
                    rotate: 45,
                    interval: 0,
                    fontSize: 10
                }
            },
            yAxis: {
                type: 'value',
                name: '销售额 (元)',
                axisLabel: {
                    formatter: '{value}'
                }
            },
            dataZoom: [
                {
                    type: 'slider', // 底部滑动条
                    show: true,
                    xAxisIndex: 0,
                    start: 0,
                    end: 100,
                    handleSize: '80%', // 滑块大小
                    handleStyle: {
                        color: '#fff',
                        borderColor: '#999',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.3)'
                    },
                    fillerColor: 'rgba(144, 197, 237, 0.2)', // 选中区域颜色
                    borderColor: '#eee'
                },
                {
                    type: 'inside', // 支持鼠标滚轮和拖动缩放
                    xAxisIndex: 0,
                    zoomOnMouseWheel: true,
                    moveOnMouseMove: true,
                    moveOnMouseWheel: false
                }
            ],
            series: seriesData.map(item => ({
                ...item,
                label: {
                    show: false,
                },
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }))
        };

        chart.setOption(option);
    } catch (error) {
        console.error('Failed to load category data:', error);
    } finally {
        chart.hideLoading();
    }

    window.addEventListener('resize', () => chart.resize());
}